<template>
  <div id="container">

    <div style="border: 1px solid #ccc">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editor"
        :default-config="toolbarConfig"
        :mode="mode"
      />
      <Editor
        v-model="contentCopy"
        style="height: 600px; overflow-y: hidden"
        :default-config="editorConfig"
        :mode="mode"
        @onCreated="onCreated"
        @onChange="onChange"
      />
    </div>

  </div>
</template>

<script>
import Vue from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

export default Vue.extend({
  name: 'RichText',
  components: { Editor, Toolbar },
  props: {
    content: {
      type: String,
      default: ''
    },
    imageurl: {
      type: String,
      required: true
    },
    maxFileSize: {
      type: Number,
      default: 5
    },
    headers: {
      type: Object,
      default: () => { return {} }
    },
    meta: {
      type: Object,
      default: () => { return {} }
    }
  },
  data() {
    return {
      form: {
        theme: ''
      },
      editor: null,
      contentCopy: '',
      toolbarConfig: {},
      editorConfig: {
        MENU_CONF: {
          uploadImage: {
            server: this.imageurl,
            timeout: 5 * 1000, // 5s
            fieldName: 'image',
            maxNumberOfFiles: 10,
            maxFileSize: this.maxFileSize * 1024 * 1024, // 5M
            headers: this.headers,
            meta: this.meta,
            onSuccess(file, res) {
              console.log('onSuccess', file, res)
            },
            onFailed(file, res) {
              console.log('onFailed', file, res)
            },
            onError(file, err, res) {
              console.error('onError', file, err, res)
            }
          }
        }
      },
      mode: 'simple', // or 'simple'，
      previewDialogVisible: false,
      previewContent: '',
      info_: ''
    }
  },
  watch: {
    content() {
      this.contentCopy = this.content
    }
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  mounted() {
  },
  methods: {
    onCreated(editor) {
      this.editor = Object.seal(editor)
      this.contentCopy = this.content
    },
    onChange() {
      this.$emit('getRichText', this.editor.getText().trim())
      this.$emit('getRichHtml', this.editor.getHtml())
    }
  }
})
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>

<style scoped>
#container {
  overflow: hidden;
}

p {
  margin: 8px 0;
}
</style>
